package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.exception.SystemException;
import com.itheima.framework.Code;
import com.itheima.framework.Result;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

//统一每一个控制器方法返回值
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    //* `http://localhost/users`	查询全部用户信息 GET（查询）
    //* `http://localhost/users/1`  查询指定用户信息 GET（查询）
    //* `http://localhost/users`    添加用户信息    POST（新增/保存）
    //* `http://localhost/users`    修改用户信息    PUT（修改/更新）
    //* `http://localhost/users/1`  删除用户信息    DELETE（删除）
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR);
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        //手动添加一个错误信息
        try {
            if(id==1){
                int i = 1/0;
            }
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_ERR,"这都能输错，笨蛋！");
        }
        Book book = bookService.selectById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败，请重新尝试";
        return new Result(code, book, msg);
    }

    @GetMapping()
    public Result getAll() {
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败，请重新尝试";
        return new Result(code, bookList, msg);
    }
}
